package com.fh.type.service.impl;/**
 * 描述:
 * Author:袁亚强
 * Date:2022/1/610:14
 */

import com.alibaba.fastjson.JSON;
import com.fh.type.entity.ShopType;
import com.fh.type.mapper.ShopTypeMapper;
import com.fh.type.service.ShopService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * created by macro on 2022/1/6,
 */
@Service
public class ShopServiceImpl implements ShopService {
    @Autowired
    private ShopTypeMapper shopTypeMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void addShopType(ShopType shopType) {
        shopTypeMapper.insert(shopType);
    }

    @Override
    public void upOrDel(ShopType shopType) {
        shopTypeMapper.upOrDel(shopType);
    }

    @Override
    public List<Map<String, Object>> queryAllTypeData() {
        List<ShopType> types = shopTypeMapper.queryTypeData();
        return getTypeList(types, 0);
    }

    private List<Map<String, Object>> getTypeList(List<ShopType> types, Integer pid) {
        List<Map<String, Object>> list = new ArrayList<>();
        for (ShopType type : types) {
            Map<String, Object> map = null;
            if (pid.equals(type.getPid())) {
                map = new HashMap<>();
                map.put("id", type.getId());
                map.put("name", type.getName());
                map.put("img", type.getImg());
                map.put("children", getTypeList(types, type.getId()));
                List children = (List) map.get("children");
                if (children.size() == 0) {
                    map.remove("children");
                }
            }
            if (map != null) {
                list.add(map);
            }
        }
        System.out.println(list);
        return list;
    }

    @Override
    public String query() {

        String typeData = (String) redisTemplate.opsForValue().get("typeData");
        if (StringUtils.isEmpty(typeData)) {
            List<ShopType> types = shopTypeMapper.queryTypeData();
            List<Map<String, Object>> typeList = getTypeList(types, 0);
            redisTemplate.opsForValue().set("typeData", JSON.toJSONString(typeList));
        }
        return typeData;
    }

    @Override
    public void reflushType() {
        //清除缓存
        redisTemplate.delete("typeData");
        // 添加缓存
        List<ShopType> types = shopTypeMapper.queryTypeData();
        List<Map<String, Object>> typeList = getTypeList(types, 0);
        redisTemplate.opsForValue().set("typeData", JSON.toJSONString(typeList));
    }
}
